package com.soosync.common;

/** JDK API */
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/** ETS API */

/**
 * Get or Release The Connection object from DataSource
 * 
 * @author Park
 * @version 1.0
 */
public class ConnectionManager {

	/** ����DataSet */
	private static HashMap dsMap = new HashMap();

	/** Context ��ʼ�������� */
	private static Context ctx = null;

	/**
	 * default constructor
	 */
	public ConnectionManager() {
	}

	/**
	 * Get the connection object from specified DataSource ( p_dsNm )
	 * 
	 * @param p_dsNm
	 *            Datasource Name
	 * @return Connection object
	 * @throws BaseException
	 */
	public static Connection getConnection(String p_dsNm) throws BaseException {
		try {
			if(p_dsNm == null || p_dsNm.equals("")){
				p_dsNm = "appSource";
			}
			DataSource ds = (DataSource) dsMap.get(p_dsNm);
			if (ds == null) {
				if (ctx == null) {
					ctx = new InitialContext();
				}
				p_dsNm = PropertyManager.getProperty(p_dsNm);
				ds = (DataSource) ctx.lookup(p_dsNm);

				// ����ds������
				dsMap.put(p_dsNm, ds);
			}
			return ds.getConnection();
		} catch (NamingException ne) {
			throw new LgtFException(ne.getMessage(), ne);
		} catch (SQLException sqle) {
			throw new LgtFException(sqle.getMessage(), sqle);
		}
	}

	/**
	 * Release the Connection object
	 * 
	 * @param p_con
	 *            Connection object for release
	 * @throws BaseException
	 */
	public static void close(Connection p_con) throws BaseException {
		try {
			p_con.close();
		} catch (SQLException sqle) {
			throw new LgtFException(sqle.getMessage(), sqle);
		}
	}
}
